import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { config } from '../smartadmin.config'
import { Router } from '@angular/router'

declare var $: any
declare var Viewer: any
@Component({
  selector: 'sa-device-info',
  templateUrl: './deviceInfo.component.html',
  styleUrls: ['./deviceInfo.component.css']
})
export class DeviceInfoComponent implements OnInit {
  @Input() deviceId: any //传输过来的值
  @Input() endTime: any //传输过来的值
  @Input() startTime: any //传输过来的值
  @Input() renewalInfo: any //传输过来的值
  @Input() iccid: any //传输过来的值
  inputParam: any = []
  deviceBaseInfo: any = {
    companyName: '',
    carNumber: '',
    deviceId: '',
    hwVersion: '',
    useTypeL1: '',
    useTypeL2: '',
    userTypeName: '',
    sensorType: '',
    productNo: '',
    iccid: '',
    driverName: '',
    phone: '',
    inputDate: '',
    userNameForCreate: '',
    sensorChannel: [],
    coef: [],
    coefT: [],
    version: '',
    carSim: ''
  }
  deviceInfo: any = {
    createTime: '',
    gpsProducer: '',
    inUser: '',
    outUser: '',
    productChannel: '',
    remake: '',
    sendAddress: '',
    sendTime: '',
    simProducer: ''
  }
  deviceRepaired_0: any = [] //待维修数组
  deviceRepaired_0_size: number = 0 //待维修的值
  deviceRepaired_1: any = [] //已维修数组
  deviceRepaired_1_size: number = 0 //已维修的值
  logForDeviceEventEntitie: any = [] //运维记录数组
  deviceRealTimeDataInfo: any = {};//设备状态
  isShowOfflineAlert: boolean = false;//是否显示离线警报提示
  offlineDiffTime: string = '';//离线时长
  weightCount: number = 0;//过磅次数
  TcarUseList = carTypeListObj.carUseList
  TcarDeatailUseList = carTypeListObj.carDeatailUseList
  cardType = 1 // 1为卡状态 2为卡信息
  currentAlertType = 1 // 当前团场类型
  cardSearchVal = '' // 卡状态/信息 模糊所搜
  cardLogList = [] // 卡日志列表
  carInfo = {} // 车辆信息
  eventObj: any = {
    '0101': '车辆安装',
    '0102': '变更车牌',
    '0103': '变更厂区',
    '0104': '车辆共享',
    '0105': '重置设备ID',
    '0106': '车辆删除',
    '0201': '固件升级',
    '0202': '更新系数',
    '0203': '远程清零',
    '0204': '设置频率',
    '0205': '远程重启',
    '0206': '恢复设置',
    '0207': '轨迹修复',
    '0208': '数据修复',
    '0301': '更换主机',
    '0302': '更换传感器',
    '0303': '更换线材',
    '0304': '更换采集器',
    '0305': '更换GPS',
    '0401': '限制进厂'
  }
  // @Output() companySelected = new EventEmitter();
  constructor(private jsonApiService: JsonApiService, private el: ElementRef, private router: Router) { }
  //传参给父组件
  ngOnInit() {
    if (this.inputParam.length == 0) {
      this.querySensor()
    } // 请求传感器列表接口
  }
  ngOnChanges() {
    this.carInfo = {}
    this.cardLogList = []
    this.cardType = 1
    this.currentAlertType = 1
    this.closeCardInfoModel()
    if (this.deviceId || this.startTime || this.endTime) {
      this.requestData(this.deviceId, this.startTime, this.endTime)
      if (this.iccid) {
        this.cardSearchVal = this.iccid.toString().toUpperCase()
      } else {
        this.cardSearchVal = ''
      }
      if (this.cardSearchVal) {
        this.getSimLog()
      }
    }
  }
  ngOnDestroy() {
    this.closeCardInfoModel()
  }
  //请求传感器类型的接口
  querySensor() {
    this.jsonApiService.http('sensorManage/querySensorList.html', '').subscribe((data) => {
      if (data.success) {
        this.inputParam = data.data
      }
    })
  }

  requestData(deviceId, startTime, endTime) {
    this.jsonApiService
      .http_get('system/queryCarInfoAll.html?deviceId=' + deviceId + '&endTime=' + endTime + '&startTime=' + startTime)
      .subscribe((data: any) => {
        if (data.success) {
          let objBase = data.data.base
          let objDeviceInfo = data.data.deviceInfo
          for (let key in objBase) {
            if (key === 'sensorChannel' && objBase[key] == null) {
              this.deviceBaseInfo[key] = []
            } else {
              this.deviceBaseInfo[key] = objBase[key] || '--'
            }
            if (objBase[key] != null) {
              if (key == 'useTypeL2') {
                this.deviceBaseInfo.userTypeName = this.getUseTypeNameL2(objBase['useTypeL2'])
              }
              if (key == 'coef') {
                let coefArr = []
                for (let i = 0; i < objBase['coef'].length; i++) {
                  let _item = objBase['coef'][i]
                  if (_item) {
                    let obj: any = {
                      value: _item,
                      index: i + 1
                    }
                    coefArr.push(obj)
                  }
                }
                this.deviceBaseInfo.coefT = coefArr
              }
            }
          }
          for (let key in objDeviceInfo) {
            if (objDeviceInfo[key] != null) {
              this.deviceInfo[key] = objDeviceInfo[key]
            }
          }
          this.deviceRepaired_0 = data.data.deviceRepaired_0
          this.deviceRepaired_0_size = data.data.deviceRepaired_0_size
          this.deviceRepaired_1 = data.data.deviceRepaired_1
          for (let i = 0; i < this.deviceRepaired_1.length; i++) {
            if (this.deviceRepaired_1[i].price) {
              let price = this.deviceRepaired_1[i].price / 100 + '元'
              var payStatus
              if (this.deviceRepaired_1[i].payStatus == 1) {
                payStatus = ' [待支付] '
              } else if (this.deviceRepaired_1[i].payStatus == 2) {
                payStatus = ' [已支付] '
              } else if (this.deviceRepaired_1[i].payStatus == 3) {
                payStatus = ' [订单取消] '
              } else if (this.deviceRepaired_1[i].payStatus == 4) {
                payStatus = ' [已完成] '
              }
              var payWay
              if (this.deviceRepaired_1[i].payWay == 0) {
                payWay = '[个人]'
              } else if (this.deviceRepaired_1[i].payWay == 1) {
                payWay = '[对公]'
              }
              this.deviceRepaired_1[i].payStr = price + payStatus + payWay
            } else {
              this.deviceRepaired_1[i].payStr = '无'
            }
          }
          this.deviceRepaired_1_size = data.data.deviceRepaired_1_size
          this.logForDeviceEventEntitie = data.data.logForDeviceEventEntitie

          // 将类型进行映射
          for (let i = 0; i < this.logForDeviceEventEntitie.length; i++) {
            this.logForDeviceEventEntitie[i].typeStr = this.eventObj[this.logForDeviceEventEntitie[i].type]
          }
        }
      })

    //设备状态(实时数据)
    this.jsonApiService
      .http_obj('system/getRealTimeData.html', { deviceId })
      .subscribe((data) => {
        if (data.success && data.data) {
          this.deviceRealTimeDataInfo = data.data
          if (JSON.stringify(this.deviceRealTimeDataInfo.markCombination) == '{}') {
            this.deviceRealTimeDataInfo.isEnterFactory = true
          } else {
            if (this.deviceRealTimeDataInfo.markCombination.fakeOnline == 1) {
              this.deviceRealTimeDataInfo.isEnterFactory = false
            } else {
              this.deviceRealTimeDataInfo.isEnterFactory = true
            }
          }
          // let carUploadDate = this.deviceRealTimeDataInfo.carUploadDate
          // let gpsUploadDate = this.deviceRealTimeDataInfo.gpsUploadDate
          // if (carUploadDate && gpsUploadDate) {
          //   let abs = Math.abs(common.mmsstoTimestamp(carUploadDate) - common.mmsstoTimestamp(gpsUploadDate))
          //   abs >= 30 * 60 * 1000 ? (this.isShowGPSAlert = true) : (this.isShowGPSAlert = false) //计算GPS是否异常:更新时间 - gps更新时间  > 30分钟    =>GPS异常
          // }
          this.getWeighbridge(deviceId)
        }
      })
  }

  //获取磅单数据:用于判断离线异常
  getWeighbridge(deviceId) {
    this.jsonApiService.http_obj("weighbridge/weightforreal.html", { deviceId, startTime: this.deviceRealTimeDataInfo.updateTime, endTime: common.getNowTime() }).subscribe(data => {
      if (data.success && data.data) {
        this.weightCount = 0;
        let diffTiem = common.mmsstoTimestamp(common.getNowTime()) - common.mmsstoTimestamp(this.deviceRealTimeDataInfo.updateTime);
        this.offlineDiffTime = common.secondToDate(diffTiem / 1000);//计算离线时长:当前时间 - 最后更新时间
        let weightData = data.data;
        for (let item of weightData) {
          if (+item.weight > 0) {
            this.isShowOfflineAlert = true;
            this.weightCount += 1;//计算榜单数
          }
        }
      }
    })
  }

  //根据编码映射对应车辆类型名称
  getUseTypeNameL2(key) {
    if (key) {
      return this.TcarDeatailUseList[key]
    } else {
      return ''
    }
  }

  repairedMonkeyPage: any
  // 维修费用明细
  repairedMonkey(value) {
    $('#repairedMonkeyInfo').show()
    this.repairedMonkeyPage = value
  }
  closeRepairedMonkey() {
    $('#repairedMonkeyInfo').hide()
  }

  isViewer: boolean = false //默认隐藏
  //显示图片组件
  viewer: any = ''
  //查看照片
  open_img(id) {
    this.jsonApiService.http_obj('deviceRepairedV2/queryById.html', { id: id }).subscribe((data) => {
      if (data.success) {
        // 返回的维修后图片列表数据
        this.beforeImageInfo = JSON.parse(JSON.stringify(data.data.beforeImageInfo))
        // 返回的维修前图片列表数据
        this.afterImageInfo = JSON.parse(JSON.stringify(data.data.afterImageInfo))
      } else {
        this.jsonApiService.message(data.message)
      }
    })

    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }

    $('#deviceInfoImg').show()
  }
  //图片放大
  bigimg() {
    // modal.show();
    if (this.isViewer && $('.viewer-container').length > 0) {
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showImg()
          })
        })
      })
    } else {
      this.showImg()
    }
  }
  showImg() {
    var that = this
    var imgList = $('.imagesDeviceInfo')[0]
    this.viewer = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    that.isViewer = true
  }
  beforeImageInfo: any = [] //维修前
  afterImageInfo: any = [] //维修后
  //关闭图片弹窗
  imgClose() {
    $('#deviceInfoImg').hide()
  }

  // 卡信息/状态搜索
  handleSearchCardList () {
    if (!this.cardSearchVal) {
      this.jsonApiService.message('请输入iccid')
      return
    }
    this.queryAndWriteSimLog()
 }
 closeCardInfoModel() {
  $('#carfListModel').hide()
 }

 // 获取卡日志
 getSimLog() {
  this.cardLogList = []
  this.jsonApiService.http_get('dataOptimization/querySimLog.html?iccid='+ this.cardSearchVal).subscribe(result => {
    if (result.success === true) {
      this.cardLogList = result.data || []
    }
  })
 }

 // SIM卡相关信息查询并写入日志
 queryAndWriteSimLog() {
  this.carInfo = {}
  this.currentAlertType = Number(this.cardType)
  let reqdata = 'iccid=' + this.cardSearchVal + '&queryTags=' + this.cardType
  this.jsonApiService.http('dataOptimization/queryAndWriteSimLog.html', reqdata).subscribe(result => {
    if (result.success === true) {
      let _carInfo = result.data || {}
      if (_carInfo.code === 0 && _carInfo.data) {
        _carInfo = Object.assign(_carInfo, _carInfo.data)
      }
      this.carInfo = _carInfo
      this.getSimLog()
      $('#carfListModel').show()
    } else {
      this.jsonApiService.message(result.message)
      this.cardLogList = []
    }
  })
 }

 handleInputKeyup (val: any) {
  if (val) {
    this.cardSearchVal = val.toUpperCase()
  }
 }

 handleCheck (row) {
  if (row.data) {
    this.carInfo =  Object.assign(row, row.data)
  } else {
    this.carInfo = row.data
  }
 
  this.currentAlertType = Number(row.dataType)
  $('#carfListModel').show()
 }
}
